#ifndef _COMM_HPP_
#define _COMM_HPP_

#include <iostream>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <cerrno>
#include <cstring>
#include <sys/ipc.h>
#include <sys/shm.h>

#define PATHNAME "."
#define PROJ_ID 0x66
#define MAX_SIZE 4096

key_t getkey()
{
    key_t k = ftok(PATHNAME,PROJ_ID);
    if(k < 0)
    {
        std::cerr<< "errno: "<< errno <<strerror(errno)<<std::endl;
        exit(1);
    }
    return k;
}

int getshmhelper(key_t k, int flags)
{
    int shmid = shmget(k, MAX_SIZE, flags);
    if(shmid < 0)
    {
        std::cerr<<errno<<":"<<strerror(errno)<<std::endl;
        exit(2);
    }
    return shmid;
}

int getshm(key_t k)
{
    return getshmhelper(k,IPC_CREAT);
}

int createshm(key_t k)
{
    return getshmhelper(k, IPC_CREAT | IPC_EXCL | 0666);
}

void* attchshm(int shmid)
{
    void* mem = shmat(shmid,nullptr,0);
    if((long long) mem==-1L)
    {
        std::cerr<<errno<<" : "<<strerror(errno)<<std::endl;
        exit(3);
    }
    return mem;
}

void detachshm(void* start)
{
    if(shmdt(start)==-1)
    {
        std::cerr<<errno<<" : "<<strerror(errno)<<std::endl;
    }
}

void delshm(int shmid)
{
    if(shmctl(shmid,IPC_RMID,nullptr)==-1)
    {
        std::cerr<<errno<<" : "<<strerror(errno)<<std::endl;
    }
}


#endif